/*
 * @LastEditors: yuSeen
 * @LastEditTime: 2022-01-09 13:46:51
 */
import { IBanner } from "@/service/api/recommendMusic/types";
import React, { memo, useEffect, useMemo, useState } from "react";
import SvgIcon from "@/components/SvgIcon/SvgIcon";
import { cloneDeep } from "lodash";
import "../style/swiper.scss";

interface ISwiperProps {
  list: IBanner[];
}

const Swiper: React.FC<ISwiperProps> = memo(({ list }) => {
  const [showNav, setShowNav] = useState<boolean>(false),
    [current, setCurrent] = useState<number>(0),
    [newList, setNewList] = useState<IBanner[]>([]);
  // 列表最后一项的索引
  const end = useMemo(() => {
    return list.length - 1;
  }, [list]);
  // 上一张图片的索引
  const lastIndex = useMemo(() => {
    if (current === 0) return end;
    return current - 1;
  }, [current]);
  // 下一张图片的索引
  const nextIndex = useMemo(() => {
    if (current === end) return 0;
    return current + 1;
  }, [current]);
  // 轮播图点击
  const itemClick = (item: IBanner) => {
    console.log(item);
  };
  useEffect(() => {
    // 计算每一项的样式
    const getStyle = (index: number) => {
      const getTranslate = () => {
        if (index === nextIndex) {
          return 160;
        }
        if (index === lastIndex) {
          return -160;
        }
        return 0;
      };
      const getIndex = () => {
        if (current === index) return 10;
        if (index === nextIndex || index === lastIndex) return 5;
        return 1;
      };
      const getOpacity = () => {
        if (current === index) return "visible";
        if (index === nextIndex || index === lastIndex) return "visible";
        return "hidden";
      };
      const style = {
        zIndex: getIndex(),
        visibility: getOpacity(),
        width: index === current ? "540px" : "430px",
        transform: `translateX(${getTranslate()}px)`,
      };
      return style;
    };
    // 替换数据，先计算好样式再渲染，避免在渲染时动态计算样式
    const replaceList = () => {
      const newList = cloneDeep(list);
      for (let i = 0; i <= end; i++) {
        newList[i].style = getStyle(i);
      }
      return newList;
    };
    setNewList(replaceList());
    
    // 自动播放， 每7s切换下一张
    const autoPlay: NodeJS.Timer = setInterval(
      () => setCurrent(nextIndex),
      7000
    );
    return (() => clearInterval(autoPlay))
  }, [list, current]);

  // 分页组件
  const pagination = () => {
    const res = [];
    for (let i = 1; i < end + 2; i++) {
      res.push(
        <span
          key={i}
          className={`dotItem ${current === i - 1 && "actived"}`}
          onMouseEnter={() => setCurrent(i - 1)}
        ></span>
      );
    }
    return res;
  };
  return (
    <>
      <div
        className="swiper"
        onMouseEnter={() => setShowNav(true)}
        onMouseLeave={() => setShowNav(false)}
      >
        {
          /* 每项 */
          newList.map((item, index) => {
            return (
              <div
                className="item"
                key={index}
                style={item.style}
                onClick={() => itemClick(item)}
              >
                <img src={item.imageUrl} />
                <span
                  className="tag"
                  style={{ backgroundColor: item.titleColor }}
                >
                  {item.typeTitle}
                </span>
              </div>
            );
          })
        }

        {
          /* 导航 */
          showNav && (
            <div className="navBox">
              <div className="nav" onClick={() => setCurrent(lastIndex)}>
                <SvgIcon name="back" fill="#fff" hover></SvgIcon>
              </div>
              <div className="nav" onClick={() => setCurrent(nextIndex)}>
                <SvgIcon
                  name="back"
                  fill="#fff"
                  hover
                  className="next"
                ></SvgIcon>
              </div>
            </div>
          )
        }
      </div>
      {/* 分页指示器 */}
      <div className="pagination flex-c-c">{pagination()}</div>
    </>
  );
});

export default Swiper;
